<template>
  <div>
    <a-form-model ref="dataForm" :model="dataForm" :rules="validatorRules" class="user-layout-login">
      <a-form-model-item prop="mobile">
        <a-input v-model="dataForm.mobile" size="large" type="text" placeholder="请输入手机号">
          <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-model-item>
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-model-item prop="smsCaptcha">
            <a-input v-model="dataForm.smsCaptcha" size="large" type="text" placeholder="请输入验证码">
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-button
              class="getCaptcha"
              tabindex="-1"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"></a-button>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { isMobile } from '@/utils/validate'
import { getSmsCaptcha } from '@/api/login'

export default {
  name: "login-phone",
  data () {
    return {
      dataForm: {
        mobile: '',
        smsCaptcha: '',
      },
      // 手机号登录用
      state: {
        time: 60,
        smsSendBtn: false,
      },
    }
  },
  computed: {
    validatorRules () {
      var validateMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback("您的手机号码格式不正确!")
        }
        callback()
      }
      return {
        mobile: [
          { required: true, message: '请输入手机号码!' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码!', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions(['PhoneLogin']),
    /**提交登录表单*/
    handleLogin () {
      this.validateFields(['mobile', 'smsCaptcha'], (err) => {
        if (!err) {
          let loginParams = {
            mobile: this.dataForm.mobile,
            smsCaptcha: this.dataForm.smsCaptcha
          }
          console.log("登录参数", loginParams)
          this.PhoneLogin(loginParams).then((res) => {
            this.$emit('success', res.result)
          }).catch((err) => {
            this.$emit('fail', err)
          });
        } else {
          this.loginBtn = false;
          this.$emit('validateFail')
        }
      })
    },
    //获取验证码
    getCaptcha (e) {
      e.preventDefault();
      let that = this;
      that.validateFields(['mobile'], (err) => {
        if (!err) {
          that.state.smsSendBtn = true;
          let interval = window.setInterval(() => {
            if (that.state.time-- <= 0) {
              that.state.time = 60;
              that.state.smsSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);

          const hide = that.$message.loading('验证码发送中..', 0);
          let smsParams = {};
          smsParams.mobile = that.dataForm.mobile;
          smsParams.smsCaptcha = "0";
          getSmsCaptcha(smsParams).then(res => {
            if (!res.success) {
              setTimeout(hide, 0);
              that.cmsFailed(res.message);
            }
            console.log(res);
            setTimeout(hide, 500);
          }).catch(err => {
            setTimeout(hide, 1);
            clearInterval(interval);
            that.state.time = 60;
            that.state.smsSendBtn = false;
            that.requestFailed(err);
          });
        }
      });
    },
    cmsFailed (err) {
      this.$notification['error']({
        message: '获取验证码失败',
        description: err,
        duration: 4,
      });
    },
    acceptMobile (mobile) {
      this.dataForm['mobile'] = mobile
    },
    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields (arr, callback) {
      let promiseArray = []
      for (let item of arr) {
        let p = new Promise((resolve, reject) => {
          this.$refs['dataForm'].validateField(item, (err) => {
            if (!err) {
              resolve();
            } else {
              reject(err);
            }
          })
        });
        promiseArray.push(p)
      }
      Promise.all(promiseArray).then(() => {
        callback()
      }).catch(err => {
        callback(err)
      })
    },
  }
}
</script>

<style scoped>

</style>
